package com.ocelot.san.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ocelot.san.dto.Balance;
import com.ocelot.san.dto.Concept;
import com.ocelot.san.dto.Operation;
import com.ocelot.san.exception.ServiceException;
import com.ocelot.san.repository.BalanceRepository;
import com.ocelot.san.type.SegmentType;

@Service
public class BalanceService {
	
	@Resource
	private BalanceRepository balanceRepository;

	@Resource
	private OperationService operationService;
	
	@Resource
	private ConceptService conceptService;

	
	public void save(Balance description) {
		balanceRepository.save(description);
	}
	
	public Balance findById(Long id) {
		return balanceRepository.findOne(id);
	}

	public void delete(Long id) {
		balanceRepository.delete(id);
	}

	public void deleteAll() {
		balanceRepository.deleteAll();
	}
	

	public List<Balance> fetchAll() {
		return balanceRepository.findAll(new Sort(Sort.Direction.ASC, "name"));
	}
	
	public List<Balance> fetchByOperation(Operation operation) {
		return balanceRepository.findByOperation(operation);
	}

	@Transactional(rollbackFor = ServiceException.class)
	public List<Balance> loadDefaultConcepts(Long operationId, SegmentType segmentType) throws ServiceException {
		List<Balance> balances = new ArrayList<Balance>();
		Operation operation = operationService.findOperationById(operationId);
		if (operation!=null) {
				balances =  fetchByOperation(operation);
				if(CollectionUtils.isEmpty(balances)) {
					List<Concept> concepts = conceptService.fetchBySegmentType(segmentType);
					if(CollectionUtils.isNotEmpty(concepts)) {
						for(Concept concept : concepts) {
							Balance balance = new Balance();
							balance.setConcept(concept);
							balance.setOperation(operation);
							balance.setAmount(0d);
							balance.setDeposit(0d);
							balance.setBalance(0d);
							save(balance);
							balances.add(balance);
						} 
					} 
				}
		} else {
			throw new ServiceException("OPERATION_NOT_FOUND");
		}
		return balances;
	}
}